package com.kikikeji.weizhuo.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;

import com.kikikeji.weizhuo.activity.core.ActivityManageIntf;

import java.util.List;

public class ActivityUtils {

    private static final java.lang.String TAG = "ActivityUtils";

    public static boolean isTopActivity(Activity activity, String hint) {
        boolean isTop = false;
        ActivityManager am = (ActivityManager)activity.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTasks = am.getRunningTasks(10);
        for (ActivityManager.RunningTaskInfo runningTask : runningTasks) {
            if(isSameActivity(activity, runningTask.topActivity) && hasRootActivity(activity)) {
                isTop = true;
                break;
            }
        }

        return isTop;
    }

    private static boolean hasRootActivity(Activity activity) {
        if (activity.getApplication() instanceof ActivityManageIntf) {
            return ((ActivityManageIntf)activity.getApplication()).hasRootActivity();
        }
        return false;
    }


    private static boolean isSameActivity(Activity activity, ComponentName componentName) {
        return componentName.getClassName().equals(activity.getClass().getName());
    }

    public static boolean pushStack(Activity activity) {
        if (isTopActivity(activity, "onCreate()")) {
            return false;
        }

        if (activity.getApplication() instanceof ActivityManageIntf) {
            ((ActivityManageIntf)activity.getApplication()).getActivityStack().addActivity(activity);
        }
        return true;
    }

    public static boolean popStack(Activity activity) {
        if (isTopActivity(activity, "onDestroy()")) {
            return false;
        }

        if (activity.getApplication() instanceof ActivityManageIntf) {
            ((ActivityManageIntf)activity.getApplication()).getActivityStack().removeActivity(activity);
            DebugLog.w(TAG, "popStack-->" + activity);
        }
        return true;
    }

}
